package com.sumainfor.wx.tenant.controller.rentadviser;

import com.alibaba.fastjson.JSONObject;
import com.sumainfor.common.config.RedisUtils;
import com.sumainfor.common.util.*;
import com.sumainfor.wx.tenant.feign.Zfeign.ZpcEpcFeign;
import com.sumainfor.wx.tenant.feign.Zfeign.ZpcGmioFeign;
import com.sumainfor.wx.tenant.feign.Zfeign.ZpcMktFeign;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 租客续签合同相关
 */
@RestController
@RequestMapping("/rentadviser/RdWxPact")
public class RdWxPactController implements Serializable {
    Logger log = LoggerFactory.getLogger(RdWxPactController.class);// 日志
    @Autowired
    private ZpcMktFeign zpcMktFeign;
    @Autowired
    private ZpcEpcFeign zpcEpcFeign;
    @Autowired
    private ZpcGmioFeign zpcGmioFeign;
    @Autowired
    private RedisUtils redisUtils;
    /**
     * 租客续签
     */
    @PostMapping("/addRerentPact")
    public JsonResult addRerentPact(@RequestBody Map<String,Object> params){
        System.out.println("租客端参数:"+params);
        return zpcMktFeign.addRerentPact(params);
    }
    /**
     * 租客端协助开门查询手机号是否该租客的室友
     */
    @PostMapping("/getRdPactTenPhoneCount")
    public JsonResult getRdPactTenPhoneCount(@RequestBody Map<String,Object> params){
        System.out.println("租客端参数:"+params);
        return zpcMktFeign.getRdPactTenPhoneCount(params);
    }
    /**
     * 协助开门 查询当前租客所签房源列表
     */
    @PostMapping("/getRdInteHouList")
    public JsonResult getRdInteHouList(@RequestBody Map<String,Object> params){
        System.out.println("租客端参数:"+params);
        return zpcMktFeign.getRdInteHouList(params);
    }
    /**
     *租客端协助开门查询房源的房间配置
     */
    @PostMapping("/getRdInteHouConInfoList")
    public JsonResult getRdInteHouConInfoList(@RequestBody Map<String,Object> params){
        System.out.println("租客端参数:"+params);
        return zpcEpcFeign.getHoInteHouConInfoList(params);
    }
    /**
     *发送键盘密码
     */
    @PostMapping("/keyboardPwdGet")
    public JsonResult keyboardPwdGet(@RequestBody Map<String,Object> params){
        JsonResult result=new JsonResult();
        if (params.get("IdentifierList")==null){
            log.debug("缺少智能设备编号:IdentifierList");
            return result.putFailed("参数不正确");
        }
        System.out.println("租客端参数:"+params);
        List<Map<String,Object>> IdentifierList=(List<Map<String,Object>>)params.get("IdentifierList");
        int num=0;
        int num2=0;//科技侠
        for (Map<String,Object> InteMap:IdentifierList){
            //0.蜂电   1.大华   2.科技侠   3.果加
            if (InteMap.get("Intelligent").toString().equals("2")){
                String DeviceLockToken=redisUtils.get("DeviceLockToken");
                //如果获取不到就重新登录
                if (DeviceLockToken==null){
                    Map<String,Object> tokenMap=new HashMap<String, Object>();
                    params.put("client_id",InteDeviceLockConfig.CLIENT_ID);
                    params.put("client_secret",InteDeviceLockConfig.CLIENT_SECRET);
                    params.put("grant_type",InteDeviceLockConfig.GRANT_TYPE_PASSWORD);
                    params.put("username",InteDeviceLockConfig.USERNAME);
                    params.put("password",InteDeviceLockConfig.PASSWORD);
                    params.put("redirect_uri",InteDeviceLockConfig.REDIRECT_URL);
                    tokenMap=InteDeviceLockUtil.oauth2Token(params);
                    if (tokenMap.get("access_token")!=null){
                        DeviceLockToken=tokenMap.get("access_token").toString();
                        //token存到redis中
                        redisUtils.set("DeviceLockToken",DeviceLockToken,Long.valueOf(tokenMap.get("expires_in").toString()));
                    }else{
                        return result.putFailed("token获取失败");
                    }
                }
                num2++;
                params.put("clientId", InteDeviceLockConfig.CLIENT_ID);//应用编号
                params.put("accessToken",DeviceLockToken);//访问令牌
                params.put("lockId",InteMap.get("Identifier"));//智能设备编号
                params.put("keyboardPwdVersion","4");//键盘密码版本, 三代锁的密码版本为4
                params.put("keyboardPwdType","1");//参数值 单次	1
                //密码有效时间
                //获取当前时间
                params.put("startDate",InteDeviceLockUtil.getTimeSign(InteDeviceLockUtil.getTimeAfter(System.currentTimeMillis(),0,"yyyy-MM-dd HH:mm:ss"),"yyyy-MM-dd HH:mm:ss"));
                //获取一个小时之后的时间
                params.put("endDate",InteDeviceLockUtil.getTimeSign(InteDeviceLockUtil.getTimeAfter(System.currentTimeMillis(),60*60*1000,"yyyy-MM-dd HH:mm:ss"),"yyyy-MM-dd HH:mm:ss"));
                params.put("date",InteDeviceLockUtil.getTimeSign());
                System.out.println("params:"+params);
                Map<String,Object> map=InteDeviceLockUtil.keyboardPwdGet(params);
                if (map.get("keyboardPwd")!=null){
                    InteMap.putAll(map);
                    num++;
                }else{
                    return result.putFailed("服务器繁忙");
                }
                InteMap.putAll(map);
            }else if(InteMap.get("Intelligent").toString().equals("3")){
                String GuoJiaToken=redisUtils.get("GuoJiaToken");
                //如果获取不到就重新登录
                if (GuoJiaToken==null){
                    Map<String,Object> guoJiaMap=new HashMap<String, Object>();
                    guoJiaMap.put("s_id",InteGuoJiaUtil.getSid());
                    guoJiaMap.put("version","1");
                    JSONObject bodyJson=new JSONObject();
                    //key
                    DESEncrypt desPlus2 = new DESEncrypt(InteGuoJiaConfig.DES_KEY);
                    //密码
                    bodyJson.put("account",InteGuoJiaConfig.ACCOUNT);
                    bodyJson.put("password",desPlus2.encrypt(InteGuoJiaConfig.PASSWORD));
                    guoJiaMap=InteGuoJiaUtil.login(guoJiaMap,bodyJson);
                    //返回的token数据
                    Map<String,Object>dataMap=(Map<String,Object>)guoJiaMap.get("data");
                    if (guoJiaMap.get("rlt_code").toString().equals("HH0000")){//HH0000 、成功
                        GuoJiaToken=dataMap.get("access_token").toString();
                        //token存到redis中
                        redisUtils.set("GuoJiaToken",GuoJiaToken,Long.valueOf(dataMap.get("expires_second").toString()));
                    }else{
                        return result.putFailed("token获取失败");
                    }
                }
                num2++;
                Map<String,Object> guoJiaMap=new HashMap<String, Object>();
                guoJiaMap.put("s_id", InteGuoJiaUtil.getSid());
                guoJiaMap.put("version","1");
                guoJiaMap.put("access_token",GuoJiaToken);
                JSONObject bodyJson=new JSONObject();
                bodyJson.put("lock_no",InteMap.get("Identifier"));//智能设备编号
                bodyJson.put("pwd_user_mobile","13020100801");
                System.out.println("guoJiaMap:"+guoJiaMap);
                //发送键密码
                Map<String,Object> map=InteGuoJiaUtil.temp_pwd(guoJiaMap,bodyJson);
                DESEncrypt desPlus2 = new DESEncrypt(InteGuoJiaConfig.DES_KEY);
                String d2="";
                try {
                    Map<String,Object> dataMap=(Map<String,Object>)map.get("data");
                    d2 = desPlus2.decrypt(DESEncrypt.byteArr2HexStr(DESEncrypt.hexStringToBytes(String.valueOf(dataMap.get("pwd_text")))));
                }catch (Exception e){
                    log.debug("键盘密码解密错误"+e);
                }
                if (map.get("rlt_code").toString().equals("HH0000")){//HH0000 请求成功
                    InteMap.put("keyboardPwd",d2);
                    InteMap.putAll(map);
                    num++;
                }else{
                    return result.putFailed("服务器繁忙");
                }
                InteMap.putAll(map);
            }
        }
        if (num==num2){
            result.put(params);
        }else{
            result.putFailed("服务器繁忙");
        }
        return result;
    }
    /**
     *申请临时密码 查询该租客的房源信息列表
     */
    @GetMapping("/getRdTemInteHouConList")
    public JsonResult getRdTemInteHouConList(@RequestParam Map<String,Object>params) {

        return zpcMktFeign.getRdTemInteHouConList(params);
    }
    /**
     *智能设备充值 查询租客所租的房子智能设备余额的和
     */
    @GetMapping("/getRdCensusHouConList")
    public JsonResult getRdCensusHouConList(@RequestParam Map<String,Object>params) {
        return zpcMktFeign.getRdCensusHouConList(params);
    }
    /**
     *智能设备充值 查询租客所租的智能设备房间
     */
    @GetMapping("/getRdInteDeviceHouConList")
    public JsonResult getRdInteDeviceHouConList(@RequestParam Map<String,Object>params) {
        return zpcMktFeign.getRdInteDeviceHouConList(params);
    }
    /**
     *租客端续签的时候查询房源是否发起过续签
     */
    @GetMapping("/getRdRenPactData")
    public JsonResult getRdRenPactData(@RequestParam Map<String,Object>params) {
        return zpcMktFeign.getRdRenPactData(params);
    }
}
